package com.mall.controller;


import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.pojo.Goods;
import com.mall.service.GoodsService;
import com.mall.util.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * <p>
 * 简单案例 - 商品表 前端控制器
 * </p>
 *
 * @author 戴浩军
 * @since 2022-06-06
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @GetMapping
    public Msg getAllGoods() {
        List<Goods> list = goodsService.list();
        return Msg.success().add("list", list);
    }

    @PostMapping
    public Msg addGood(@RequestBody Goods good) {
        System.out.println(good.getId());
//        response.setContentType("image/jpeg;image/jpeg;image/png");
//        response.setContentType("application/x-msdownload;charset=utf-8");
        if (good.getId() != null) {
            goodsService.updateById(good);
            return Msg.success("修改成功！");
        }else {
//            System.out.println(good);
            goodsService.save(good);
            return Msg.success("添加成功");
        }


    }

    @DeleteMapping("{id}")
    public Msg deleteGood(@PathVariable Integer id) {
        goodsService.removeById(id);
        return Msg.success().add("this", goodsService.getById(id));
    }

    //分页条件查询
    @GetMapping("/page/{current}/{limit}")
    public Msg pageSelect(@PathVariable Integer current,
                          @PathVariable Integer limit,
                          @RequestBody(required = false) Goods goodQueryVo){
        Page<Goods> page = new Page<Goods>(current, limit);
        //构建分页对象

        QueryWrapper<Goods> qw = new QueryWrapper<>();
        //构建条件对象
        if(StringUtils.isEmpty(goodQueryVo)){
           return Msg.success().add("data",goodsService.page(page,qw));
        }
//        如果条件不为空则构建条件
        qw.like("title",goodQueryVo.getTitle());

        qw.le("price", goodQueryVo.getTitle());

        qw.like("comment",goodQueryVo.getComment());

        return Msg.success().add("data",goodsService.page(page,qw));

    }


}

